<template>
  <div class="upload-file">
    <el-upload
      action="#"
      :before-upload="handleBeforeUpload"
      list-type="picture-card"
      :limit="1"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :headers="headers"
      :on-remove="handleDelete"
      class="upload-file-uploader"
      ref="upload"
      :http-request="handleUpload"
    >
      <!-- 上传按钮 -->
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {uploadToBase64} from '@/api/boomMonitor/topology'

export default {
  props: {
    // 值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 1,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["svg", 'png', 'jpg'],
    }
  },
  data() {
    return {
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
    };
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);

        });
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传单个文件`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("deleteNodeImage", '');
    },
    handleUpload: function (data) {
      const file = data.file;
      // 根据后台需求数据格式
      const form = new FormData();
      let _this = this;
      // 文件对象
      form.append("file", file);
      uploadToBase64(form).then(response=> {
        _this.$emit("addNodeImage", response);
      });
    },
    clearFiles: function () {
      this.$refs.upload.clearFiles();
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
